package com.biz.primus.management.commodity.controller;

import com.biz.primus.commodity.vo.BrandQueryVo;
import com.biz.primus.commodity.vo.CategoryQueryVo;
import com.biz.primus.commodity.vo.backend.BrandListItemVo;
import com.biz.primus.commodity.vo.backend.CategoryListItemVo;
import com.biz.primus.commodity.vo.backend.UpdateBrandVo;
import com.biz.primus.common.vo.SpringPageVO;
import com.biz.primus.management.base.controller.AbstractBaseController;
import com.biz.primus.management.commodity.feign.BrandFeignClient;
import com.biz.primus.management.commodity.feign.CategoryFeignClient;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

/**
 * @author jiangnan
 * @Description: TODO
 * @create 2017-10-12-下午2:19
 */
@Controller
@RequestMapping("management/brand")
public class BrandController extends AbstractBaseController {

    private final BrandFeignClient brandFeignClient;

    private final CategoryFeignClient categoryFeignClient;

    public BrandController(BrandFeignClient brandFeignClient, CategoryFeignClient categoryFeignClient) {
        this.brandFeignClient = brandFeignClient;
        this.categoryFeignClient = categoryFeignClient;
    }

    @GetMapping(value = "list")
    @ResponseBody
    @PreAuthorize("hasAuthority('OPT_BRAND_LIST')")
    public ModelAndView list(@ModelAttribute("reqVo") BrandQueryVo reqVo) {
        SpringPageVO<BrandListItemVo> result = brandFeignClient.findAll(reqVo);
        SpringPageVO<CategoryListItemVo> categories = categoryFeignClient.findAll(new CategoryQueryVo());
        return new ModelAndView("brand/list", "pages", result).addObject("categories",categories);
    }

    @RequestMapping("{id}")
    @PreAuthorize("hasAuthority('OPT_BRAND_DETAIL')")
    public ModelAndView edit(@PathVariable Long id) {
        return new ModelAndView("brand/detail")
                .addObject("brand", brandFeignClient.getBrandById(id))
                .addObject("categories",categoryFeignClient.findAll(new CategoryQueryVo()));
    }

    @PostMapping("save")
    @PreAuthorize("hasAuthority('OPT_BRAND_UPDATE')")
    public ModelAndView save(@Valid UpdateBrandVo updateBrandVo, BindingResult result) {
        error(result);
        brandFeignClient.update(updateBrandVo);
        return new ModelAndView("redirect:/management/brand/list");
    }

}
